<template>
  <div class="database-management">
    <div class="page-header">
      <h1>数据库实例管理</h1>
      <p class="page-description">选择数据源后管理其下的数据库实例，支持创建、删除和配置数据库</p>
    </div>

    <!-- 数据源选择器 -->
    <div class="datasource-selector">
      <el-card shadow="never" class="selector-card">
        <div class="selector-content">
          <div class="selector-label">
            <el-icon><DataBoard /></el-icon>
            <span>选择数据源:</span>
          </div>
          <el-select
            v-model="selectedDataSourceId"
            placeholder="请选择数据源"
            style="width: 300px"
            @change="handleDataSourceChange"
            :loading="loadingDataSources"
          >
            <el-option
              v-for="ds in dataSources"
              :key="ds.id"
              :label="`${ds.name} (${getDatabaseTypeText(ds.type)})`"
              :value="ds.id"
            />
          </el-select>
          <el-button @click="refreshDataSources" :icon="Refresh" :loading="loadingDataSources">
            刷新数据源
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 数据库管理区域 -->
    <div v-if="selectedDataSource" class="database-section">
      <div class="section-header">
        <div class="section-title">
          <h2>{{ selectedDataSource.name }} - 数据库实例</h2>
          <el-tag type="info">{{ getDatabaseTypeText(selectedDataSource.type) }}</el-tag>
        </div>
        <div class="section-actions">
          <el-button type="primary" @click="showCreateDialog" :icon="Plus">
            创建数据库
          </el-button>
          <el-button @click="refreshDatabases" :icon="Refresh" :loading="loadingDatabases">
            刷新
          </el-button>
        </div>
      </div>

      <div class="search-toolbar">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索数据库名称"
          :prefix-icon="Search"
          clearable
          style="width: 300px"
        />
      </div>

      <el-table 
        :data="filteredDatabases" 
        v-loading="loadingDatabases" 
        stripe 
        style="width: 100%"
      >
        <el-table-column prop="name" label="数据库名称" min-width="200">
          <template #default="{ row }">
            <div class="database-name-cell">
              <el-icon class="database-icon"><Collection /></el-icon>
              <span class="database-name">{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="tableCount" label="表数量" width="120" align="right">
          <template #default="{ row }">
            <span>{{ row.tableCount || 0 }} 个</span>
          </template>
        </el-table-column>

        <el-table-column prop="size" label="数据库大小" width="120" align="right">
          <template #default="{ row }">
            <span>{{ formatSize(row.size) }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="charset" label="字符集" width="120">
          <template #default="{ row }">
            <el-tag size="small" type="info">{{ row.charset || 'utf8mb4' }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            <span>{{ formatDate(row.createTime) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="280">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="viewTables(row)">
              查看表
            </el-button>
            <el-button size="small" @click="manageDatabaseUsers(row)">
              用户管理
            </el-button>
            <el-button size="small" @click="backupDatabase(row)">
              备份
            </el-button>
            <el-button size="small" @click="analyzeDatabase(row)">
              分析
            </el-button>
            <el-button size="small" type="danger" @click="deleteDatabase(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 空状态 -->
    <div v-else class="empty-state">
      <el-empty description="请先选择一个数据源">
        <el-button type="primary" @click="goToDataSourceManagement">
          去管理数据源
        </el-button>
      </el-empty>
    </div>

    <!-- 创建数据库对话框 -->
    <el-dialog
      v-model="createDialogVisible"
      title="创建数据库"
      width="500px"
      @close="resetCreateForm"
    >
      <el-form
        ref="createFormRef"
        :model="createFormData"
        :rules="createFormRules"
        label-width="100px"
      >
        <el-form-item label="数据库名称" prop="name">
          <el-input
            v-model="createFormData.name"
            placeholder="请输入数据库名称"
          />
        </el-form-item>
        
        <el-form-item label="字符集" prop="charset">
          <el-select 
            v-model="createFormData.charset" 
            style="width: 100%" 
            @change="onCharsetChange"
            placeholder="请选择字符集"
          >
            <el-option 
              v-for="charset in availableCharsets" 
              :key="charset.value"
              :label="charset.label" 
              :value="charset.value" 
            />
          </el-select>
        </el-form-item>

        <el-form-item label="排序规则" prop="collation">
          <el-select 
            v-model="createFormData.collation" 
            style="width: 100%"
            placeholder="请选择排序规则"
            :disabled="!createFormData.charset"
          >
            <el-option 
              v-for="collation in availableCollations" 
              :key="collation.value"
              :label="collation.label" 
              :value="collation.value" 
            />
          </el-select>
        </el-form-item>

        <!-- MySQL特有选项 -->
        <template v-if="currentDatabaseType === 'mysql'">
          <el-form-item label="存储引擎">
            <el-select v-model="createFormData.storageEngine" style="width: 100%">
              <el-option 
                v-for="engine in currentTypeConfig.storageEngines" 
                :key="engine.value"
                :label="engine.label" 
                :value="engine.value" 
              />
            </el-select>
          </el-form-item>
        </template>

        <!-- PostgreSQL特有选项 -->
        <template v-if="currentDatabaseType === 'postgresql'">
          <el-form-item label="模板数据库">
            <el-select v-model="createFormData.template" style="width: 100%">
              <el-option 
                v-for="template in currentTypeConfig.templates" 
                :key="template.value"
                :label="template.label" 
                :value="template.value" 
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="所有者">
            <el-input
              v-model="createFormData.owner"
              placeholder="请输入数据库所有者"
            />
          </el-form-item>
        </template>

        <el-form-item label="备注">
          <el-input
            v-model="createFormData.comment"
            type="textarea"
            :rows="3"
            placeholder="请输入数据库备注（可选）"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="createDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="createDatabase" :loading="creating">
            创建
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Refresh,
  Search,
  DataBoard,
  Collection
} from '@element-plus/icons-vue'

const router = useRouter()

// 响应式数据
const loadingDataSources = ref(false)
const loadingDatabases = ref(false)
const creating = ref(false)
const selectedDataSourceId = ref(null)
const searchKeyword = ref('')
const createDialogVisible = ref(false)
const createFormRef = ref()

// 数据源列表
const dataSources = ref([
  {
    id: 1,
    name: '主数据库',
    type: 'mysql',
    host: 'localhost',
    port: 3306,
    status: 'connected'
  },
  {
    id: 2,
    name: '测试数据库',
    type: 'postgresql',
    host: '192.168.1.100',
    port: 5432,
    status: 'connected'
  }
])

// 数据库列表
const databases = ref([])

// 数据库类型特有配置
const databaseTypeConfigs = {
  mysql: {
    charsets: [
      { label: 'utf8mb4 (推荐)', value: 'utf8mb4' },
      { label: 'utf8', value: 'utf8' },
      { label: 'latin1', value: 'latin1' },
      { label: 'gbk', value: 'gbk' },
      { label: 'ascii', value: 'ascii' }
    ],
    collations: {
      utf8mb4: [
        { label: 'utf8mb4_unicode_ci (推荐)', value: 'utf8mb4_unicode_ci' },
        { label: 'utf8mb4_general_ci', value: 'utf8mb4_general_ci' },
        { label: 'utf8mb4_bin', value: 'utf8mb4_bin' },
        { label: 'utf8mb4_0900_ai_ci', value: 'utf8mb4_0900_ai_ci' }
      ],
      utf8: [
        { label: 'utf8_unicode_ci', value: 'utf8_unicode_ci' },
        { label: 'utf8_general_ci', value: 'utf8_general_ci' },
        { label: 'utf8_bin', value: 'utf8_bin' }
      ],
      latin1: [
        { label: 'latin1_swedish_ci', value: 'latin1_swedish_ci' },
        { label: 'latin1_general_ci', value: 'latin1_general_ci' },
        { label: 'latin1_bin', value: 'latin1_bin' }
      ],
      gbk: [
        { label: 'gbk_chinese_ci', value: 'gbk_chinese_ci' },
        { label: 'gbk_bin', value: 'gbk_bin' }
      ],
      ascii: [
        { label: 'ascii_general_ci', value: 'ascii_general_ci' },
        { label: 'ascii_bin', value: 'ascii_bin' }
      ]
    },
    defaultCharset: 'utf8mb4',
    defaultCollation: 'utf8mb4_unicode_ci',
    storageEngines: [
      { label: 'InnoDB (推荐)', value: 'InnoDB' },
      { label: 'MyISAM', value: 'MyISAM' },
      { label: 'Memory', value: 'Memory' }
    ]
  },
  postgresql: {
    charsets: [
      { label: 'UTF8 (推荐)', value: 'UTF8' },
      { label: 'LATIN1', value: 'LATIN1' },
      { label: 'SQL_ASCII', value: 'SQL_ASCII' },
      { label: 'WIN1252', value: 'WIN1252' }
    ],
    collations: {
      UTF8: [
        { label: 'zh_CN.UTF-8', value: 'zh_CN.UTF-8' },
        { label: 'en_US.UTF-8 (推荐)', value: 'en_US.UTF-8' },
        { label: 'C', value: 'C' },
        { label: 'POSIX', value: 'POSIX' }
      ],
      LATIN1: [
        { label: 'en_US.ISO8859-1', value: 'en_US.ISO8859-1' },
        { label: 'C', value: 'C' }
      ],
      SQL_ASCII: [
        { label: 'C', value: 'C' },
        { label: 'POSIX', value: 'POSIX' }
      ],
      WIN1252: [
        { label: 'en_US.CP1252', value: 'en_US.CP1252' }
      ]
    },
    defaultCharset: 'UTF8',
    defaultCollation: 'en_US.UTF-8',
    templates: [
      { label: 'template1 (默认)', value: 'template1' },
      { label: 'template0', value: 'template0' }
    ]
  }
}

// 创建表单数据
const createFormData = reactive({
  name: '',
  charset: '',
  collation: '',
  comment: '',
  // MySQL特有字段
  storageEngine: 'InnoDB',
  // PostgreSQL特有字段
  template: 'template1',
  owner: 'postgres'
})

// 创建表单验证规则
const createFormRules = {
  name: [
    { required: true, message: '请输入数据库名称', trigger: 'blur' },
    { pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/, message: '数据库名称只能包含字母、数字和下划线，且以字母开头', trigger: 'blur' }
  ],
  charset: [
    { required: true, message: '请选择字符集', trigger: 'change' }
  ],
  collation: [
    { required: true, message: '请选择排序规则', trigger: 'change' }
  ]
}

// 计算属性
const selectedDataSource = computed(() => {
  return dataSources.value.find(ds => ds.id === selectedDataSourceId.value)
})

const currentDatabaseType = computed(() => {
  return selectedDataSource.value?.type || 'mysql'
})

const currentTypeConfig = computed(() => {
  return databaseTypeConfigs[currentDatabaseType.value] || databaseTypeConfigs.mysql
})

const availableCharsets = computed(() => {
  return currentTypeConfig.value.charsets
})

const availableCollations = computed(() => {
  if (!createFormData.charset) return []
  return currentTypeConfig.value.collations[createFormData.charset] || []
})

const filteredDatabases = computed(() => {
  if (!searchKeyword.value) return databases.value
  return databases.value.filter(db => 
    db.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

// 方法
const getDatabaseTypeText = (type) => {
  const typeMap = {
    mysql: 'MySQL',
    postgresql: 'PostgreSQL',
    sqlserver: 'SQL Server',
    oracle: 'Oracle'
  }
  return typeMap[type] || type
}

const formatSize = (size) => {
  if (!size) return '0 B'
  const units = ['B', 'KB', 'MB', 'GB', 'TB']
  let index = 0
  while (size >= 1024 && index < units.length - 1) {
    size /= 1024
    index++
  }
  return `${size.toFixed(1)} ${units[index]}`
}

const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN')
}

const handleDataSourceChange = (dataSourceId) => {
  if (dataSourceId) {
    loadDatabases(dataSourceId)
  } else {
    databases.value = []
  }
}

const loadDatabases = async (dataSourceId) => {
  loadingDatabases.value = true
  try {
    // 模拟加载数据库列表
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟不同数据源的数据库
    const mockDatabases = {
      1: [ // MySQL
        {
          name: 'ecommerce',
          tableCount: 25,
          size: 1024 * 1024 * 150, // 150MB
          createTime: '2024-01-15T10:30:00Z',
          charset: 'utf8mb4'
        },
        {
          name: 'user_center',
          tableCount: 12,
          size: 1024 * 1024 * 80, // 80MB
          createTime: '2024-02-01T14:20:00Z',
          charset: 'utf8mb4'
        },
        {
          name: 'logs',
          tableCount: 5,
          size: 1024 * 1024 * 1024 * 2, // 2GB
          createTime: '2024-01-10T09:15:00Z',
          charset: 'utf8mb4'
        }
      ],
      2: [ // PostgreSQL
        {
          name: 'test_db',
          tableCount: 8,
          size: 1024 * 1024 * 45, // 45MB
          createTime: '2024-03-01T11:00:00Z',
          charset: 'UTF8'
        },
        {
          name: 'analytics',
          tableCount: 15,
          size: 1024 * 1024 * 500, // 500MB
          createTime: '2024-02-15T16:45:00Z',
          charset: 'UTF8'
        }
      ]
    }
    
    databases.value = mockDatabases[dataSourceId] || []
  } catch (error) {
    ElMessage.error('加载数据库列表失败')
  } finally {
    loadingDatabases.value = false
  }
}

const refreshDataSources = async () => {
  loadingDataSources.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 800))
    ElMessage.success('数据源列表已刷新')
  } finally {
    loadingDataSources.value = false
  }
}

const refreshDatabases = async () => {
  if (selectedDataSourceId.value) {
    await loadDatabases(selectedDataSourceId.value)
    ElMessage.success('数据库列表已刷新')
  }
}

const showCreateDialog = () => {
  if (!selectedDataSourceId.value) {
    ElMessage.warning('请先选择数据源')
    return
  }
  createDialogVisible.value = true
  resetCreateForm()
}

const resetCreateForm = () => {
  const config = currentTypeConfig.value
  Object.assign(createFormData, {
    name: '',
    charset: config.defaultCharset,
    collation: config.defaultCollation,
    comment: '',
    // MySQL特有字段
    storageEngine: 'InnoDB',
    // PostgreSQL特有字段
    template: 'template1',
    owner: 'postgres'
  })
  if (createFormRef.value) {
    createFormRef.value.clearValidate()
  }
}

const onCharsetChange = (charset) => {
  // 当字符集改变时，重置排序规则为该字符集的第一个选项
  const collations = currentTypeConfig.value.collations[charset]
  if (collations && collations.length > 0) {
    createFormData.collation = collations[0].value
  } else {
    createFormData.collation = ''
  }
}

const createDatabase = async () => {
  if (!createFormRef.value) return
  
  try {
    await createFormRef.value.validate()
    creating.value = true
    
    // 模拟创建数据库
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    const newDatabase = {
      name: createFormData.name,
      tableCount: 0,
      size: 0,
      createTime: new Date().toISOString(),
      charset: createFormData.charset,
      comment: createFormData.comment,
      type: currentDatabaseType.value,
      // 根据数据库类型添加特有属性
      ...(currentDatabaseType.value === 'mysql' ? {
        storageEngine: createFormData.storageEngine,
        collation: createFormData.collation
      } : {
        template: createFormData.template,
        owner: createFormData.owner,
        encoding: createFormData.charset,
        lcCollate: createFormData.collation,
        lcCtype: createFormData.collation
      })
    }
    
    databases.value.push(newDatabase)
    
    // 根据数据库类型显示不同的成功消息
    const typeText = currentDatabaseType.value === 'mysql' ? 'MySQL' : 'PostgreSQL'
    const extraInfo = currentDatabaseType.value === 'mysql' 
      ? `字符集: ${createFormData.charset}, 存储引擎: ${createFormData.storageEngine}`
      : `编码: ${createFormData.charset}, 模板: ${createFormData.template}`
    
    ElMessage.success(`${typeText} 数据库 "${createFormData.name}" 创建成功 (${extraInfo})`)
    createDialogVisible.value = false
  } catch {
    ElMessage.warning('请完善表单信息')
  } finally {
    creating.value = false
  }
}



const backupDatabase = async (database) => {
  try {
    ElMessage.info(`开始备份数据库 "${database.name}"...`)
    // 模拟备份过程
    await new Promise(resolve => setTimeout(resolve, 2000))
    ElMessage.success(`数据库 "${database.name}" 备份完成`)
  } catch (error) {
    ElMessage.error('备份失败')
  }
}

const analyzeDatabase = (database) => {
  ElMessage.info(`正在分析数据库 "${database.name}" 的统计信息...`)
  // 这里可以打开一个详细的分析对话框
}

const deleteDatabase = async (database) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除数据库 "${database.name}" 吗？此操作不可恢复，将删除所有数据！`,
      '危险操作',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'error',
        confirmButtonClass: 'el-button--danger'
      }
    )
    
    const index = databases.value.findIndex(db => db.name === database.name)
    if (index > -1) {
      databases.value.splice(index, 1)
      ElMessage.success(`数据库 "${database.name}" 已删除`)
    }
  } catch {
    // 用户取消删除
  }
}

const viewTables = (database) => {
  // 跳转到表管理页面，并传递数据源和数据库信息
  router.push({
    name: 'TableManagement',
    query: {
      dataSourceId: selectedDataSourceId.value,
      databaseName: database.name
    }
  })
}

const manageDatabaseUsers = (database) => {
  ElMessage.info(`数据库 "${database.name}" 的用户管理功能开发中...`)
}

const goToDataSourceManagement = () => {
  router.push({ name: 'DataSourceManagement' })
}

onMounted(() => {
  // 组件挂载后的初始化逻辑
})
</script>

<style scoped>
.database-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.page-description {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

.datasource-selector {
  margin-bottom: 24px;
}

.selector-card {
  border: 1px solid #e5e7eb;
}

.selector-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.selector-label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  color: #374151;
  white-space: nowrap;
}

.database-section {
  margin-top: 24px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.section-title h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #1f2937;
}

.section-actions {
  display: flex;
  gap: 12px;
}

.search-toolbar {
  margin-bottom: 20px;
}

.database-name-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.database-icon {
  color: #409eff;
  font-size: 16px;
}

.database-name {
  font-weight: 500;
  color: #303133;
}



.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

@media (max-width: 768px) {
  .section-header {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }
  
  .selector-content {
    flex-direction: column;
    align-items: stretch;
  }
}
</style>